const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    openid: '',
    babyId: '',
    baby: {},
    logData: [],
    logDataID: {},
    templateData: [],
    page: 1,
    size: 10,
    showForm: '',
    formTab: 'logs',
    logTab: '',
    babyTab: '',
    logFormContent: '',
    logFormScore: '',
    templateForm: '',
    addTab: '',
    editTab: '',
    templateNeedLoad: true,
    templateIsEdit: false,
    templateEdit: {}
  },
  loadBaby: function () {
    let that = this,
      data = that.data,
      openid = data.openid,
      babyId = data.babyId
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.cloud.callFunction({
      name: 'dbLookup',
      data: {
        db_name: 'user_baby',
        lookup: {
          from: 'baby',
          localField: 'baby_id',
          foreignField: '_id',
          as: 'info'
        },
        match: {
          _openid: openid,
          baby_id: babyId,
          deled: false,
          'info.deled': false
        },
        sort: {
          create_time: -1
        }
      }
    }).then(res => {
      wx.hideLoading()
      if (res.result.list.length > 0) {
        let baby = res.result.list[0]
        that.setData({
          baby: res.result.list[0]
        }, () => {
          wx.setNavigationBarTitle({
            title: '我的宝宝 - ' + baby.info[0].name
          })
          that.loadLog(true)
        })
      } else {
        console.log('222')
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }
    }).catch(err => {
      console.log('221112', err)
      wx.hideLoading()
      wx.reLaunch({
        url: '/pages/index/index'
      })
    })
  },
  loadLog: function (isNew) {
    let that = this,
      data = that.data,
      baby = data.baby
    db.collection('logs').where({
      baby_id: baby.info[0]._id,
      deled: false
    }).count({
      success: res => {
        if (res.total > 0) {
          let size = data.size,
            page = data.page,
            total = Math.ceil(res.total / size)
          if (isNew) {
            that.setData({
              page: 1
            })
            page = 1
          }
          if (page <= total) {
            wx.cloud.callFunction({
              name: 'dbLookup',
              data: {
                db_name: 'logs',
                lookup: {
                  from: 'users',
                  localField: '_openid',
                  foreignField: '_openid',
                  as: 'user'
                },
                match: {
                  baby_id: baby.info[0]._id,
                  deled: false
                },
                sort: {
                  create_time: -1
                },
                skip: ((page - 1) * size),
                limit: size
              }
            }).then(res => {
              page++
              let log = res.result.list,
                length = log.length,
                logData = data.logData,
                logDataID = data.logDataID
              if (isNew && isNew == 1) {
                logData = []
                logDataID = {}
              }
              if (length > 0) {
                for (let i = 0; i < length; i++) {
                  if (!logDataID['log_' + log[i]._id]) {
                    log[i].date = that.timeRend(log[i].create_time)
                    logData.push(log[i])
                    logDataID['log_' + log[i]._id] = 1
                  }
                }
              }
              that.setData({
                logData: logData,
                logDataID: logDataID,
                page: page
              })
            })
          }
        } else {
          that.setData({
            logData: [],
            logDataID: {}
          })
        }
      }
    })
  },
  timeRend: function (time) {
    let date = new Date(time)
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
  },
  loadTemplate: function () {
    let that = this,
      data = that.data,
      openid = data.openid
    db.collection('template').where({
      _openid: openid,
      deled: false
    }).orderBy('create_time', 'desc').get({
      success: res => {
        that.setData({
          templateData: res.data,
          templateNeedLoad: false
        })
      }
    })
  },
  tabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab,
      form = e.currentTarget.dataset.form
    that.setData({
      showForm: form,
      formTab: tab
    })
    if (form == 'log') {
      that.setData({
        logTab: 'add'
      })
    } else if (form == 'baby') {
      that.setData({
        babyTab: 'info'
      })
    }
  },
  xTap: function () {
    let that = this
    that.setData({
      showForm: '',
      formTab: 'logs',
      logTab: '',
      babyTab: '',
      logFormContent: '',
      logFormScore: '',
      templateForm: '',
      addTab: '',
      editTab: '',
      templateIsEdit: false,
      templateEdit: {}
    })
  },
  logTabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab
    that.setData({
      logTab: tab
    })
    if (tab == 'template') {
      that.templateListTap()
    } else {
      that.setData({
        templateForm: '',
        addTab: '',
        editTab: '',
        templateIsEdit: false,
        templateEdit: {}
      })
    }
  },
  templateListTap: function () {
    let that = this,
      data = that.data,
      templateNeedLoad = data.templateNeedLoad
    that.setData({
      logTab: 'template'
    })
    if (templateNeedLoad) {
      that.loadTemplate()
    }
  },
  logSubmit: function (e) {
    let that = this,
      data = that.data,
      baby = data.baby,
      content = e.detail.value.content,
      score = +e.detail.value.score
    if (isNaN(score)) score = 0
    if (content.length == 0 || score == 0) {
      wx.showToast({
        title: '请输入内容、积分',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      let time = new Date().getTime()
      if (data.logTab == 'sub') score = 0 - score
      db.collection('logs').add({
        data: {
          baby_id: baby.info[0]._id,
          content: content,
          score: score,
          deled: false,
          create_time: time
        },
        success: res => {
          wx.hideLoading()
          that.xTap()
          that.loadLog(true)
          db.collection('baby').doc(baby.info[0]._id).get({
            success: res => {
              console.log(res)
              let current = res.data
              current.score += score
              wx.cloud.callFunction({
                name: 'dbUpdate',
                data: {
                  db_name: 'baby',
                  where: {
                    _id: current._id
                  },
                  update: {
                    score: current.score
                  }
                }
              })
              baby.info[0].score = current.score
              that.setData({
                baby: baby
              })
            }
          })
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          })
        }
      })
    }
  },
  babyTabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab
    that.setData({
      babyTab: tab
    })
  },
  babySubmit: function (e) {
    let that = this,
      data = that.data,
      baby = data.baby,
      name = e.detail.value.name
    if (name.length == 0) {
      wx.showToast({
        title: '请输入宝宝昵称',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.cloud.callFunction({
        name: 'dbUpdate',
        data: {
          db_name: 'baby',
          where: {
            _id: baby.info[0]._id
          },
          update: {
            name: name
          }
        },
        success: res => {
          wx.hideLoading()
          that.xTap()
          that.loadBaby()
        },
        fail: err => {
          wx.hideLoading()
          console.log(err)
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      })
    }
  },
  bindSubmit: function (e) {
    let that = this,
      data = that.data,
      baby = data.baby,
      oid = e.detail.value.oid,
      password = e.detail.value.password
    if (oid.length == 0 || password.length == 0) {
      wx.showToast({
        title: '请输入宝宝ID、密码',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      if (oid != baby.info[0].oid) {
        db.collection('baby').where({
          oid: oid
        }).get({
          success: res => {
            if (res.data.length > 0) {
              wx.hideLoading()
              wx.showToast({
                title: 'ID已被使用，请使用其他ID',
                icon: 'none'
              })
            } else {
              that.editBaby({
                oid: oid,
                password: password
              })
            }
          },
          fail: err => {
            wx.hideLoading()
            wx.showToast({
              title: '修改失败',
              icon: 'none'
            })
          }
        })
      } else {
        that.editBaby({
          password: password
        })
      }
    }
  },
  editBaby: function (args) {
    let that = this,
      data = that.data,
      baby = data.baby
    db.collection('baby').doc(baby.info[0]._id).update({
      data: args,
      success: res => {
        wx.hideLoading()
        that.xTap()
        that.loadBaby()
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '修改失败',
          icon: 'none'
        })
      }
    })
  },
  templateAddTap: function () {
    let that = this
    that.setData({
      templateForm: 'add',
      addTab: 'add'
    })
  },
  templateEditTap: function () {
    let that = this,
      data = that.data,
      templateIsEdit = data.templateIsEdit
    that.setData({
      templateIsEdit: !templateIsEdit
    })
  },
  templateTap: function (e) {
    let that = this,
      data = that.data,
      templateIsEdit = data.templateIsEdit,
      templateData = data.templateData,
      length = templateData.length,
      id = e.currentTarget.dataset.id,
      currentData = null
    if (length > 0) {
      for (let i = 0; i < length; i++) {
        if (templateData[i]._id == id) {
          currentData = templateData[i]
          break
        }
      }
    }
    if (templateIsEdit) {
      if (currentData) {
        let tab = currentData.score < 0 ? 'sub' : 'add'
        currentData.score = Math.abs(currentData.score)
        that.setData({
          templateForm: 'edit',
          templateEdit: currentData,
          editTab: tab
        })
      }
    } else {
      let logTab = 'add',
        logFormContent = '',
        logFormScore = ''
      if (currentData) {
        logFormContent = currentData.content
        logFormScore = Math.abs(currentData.score)
        if (currentData.score < 0) logTab = 'sub'
      }
      that.setData({
        logTab: logTab,
        logFormContent: logFormContent,
        logFormScore: logFormScore
      })
    }
  },
  templateDelTap: function (e) {
    let that = this,
      data = that.data,
      templateData = data.templateData,
      length = templateData.length,
      id = e.currentTarget.dataset.id,
      currentData = null
    if (length > 0) {
      for (let i = 0; i < length; i++) {
        if (templateData[i]._id == id) {
          currentData = templateData[i]
          break
        }
      }
    }
    if (currentData) {
      wx.showModal({
        title: '删除提示',
        content: '确定要删除这条模板？',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '加载中',
              mask: true
            })
            db.collection('template').doc(currentData._id).update({
              data: {
                deled: true
              },
              success: res => {
                wx.hideLoading()
                that.loadTemplate()
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    }
  },
  addTabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab
    that.setData({
      addTab: tab
    })
  },
  addSubmit: function (e) {
    let that = this,
      data = that.data,
      content = e.detail.value.content,
      score = +e.detail.value.score
    if (isNaN(score)) score = 0
    if (content.length == 0 || score == 0) {
      wx.showToast({
        title: '请输入内容、积分',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      let time = new Date().getTime()
      if (data.addTab == 'sub') score = 0 - score
      db.collection('template').add({
        data: {
          content: content,
          score: score,
          deled: false,
          create_time: time
        },
        success: res => {
          wx.hideLoading()
          that.templateCancelTap()
          that.loadTemplate()
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          })
        }
      })
    }
  },
  editTabTap: function (e) {
    let that = this,
      tab = e.currentTarget.dataset.tab
    that.setData({
      editTab: tab
    })
  },
  editSubmit: function (e) {
    let that = this,
      data = that.data,
      content = e.detail.value.content,
      score = +e.detail.value.score
    if (isNaN(score)) score = 0
    if (content.length == 0 || score == 0) {
      wx.showToast({
        title: '请输入内容、积分',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      if (data.editTab == 'sub') score = 0 - score
      db.collection('template').doc(data.templateEdit._id).update({
        data: {
          content: content,
          score: score
        },
        success: res => {
          wx.hideLoading()
          that.templateCancelTap()
          that.loadTemplate()
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          })
        },
        fail: err => {
          wx.hideLoading()
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      })
    }
  },
  templateCancelTap: function () {
    let that = this
    that.setData({
      templateForm: '',
      addTab: '',
      editTab: '',
      templateEdit: {}
    })
  },
  onLoad: function (options) {
    let that = this,
      openid = wx.getStorageSync('openid') || '',
      babyId = ''
    if (options.id && options.id.length > 0) babyId = options.id
    if (babyId.length > 0 && openid.length > 0) {
      that.setData({
        openid: openid,
        babyId: babyId
      }, () => {
        that.loadBaby()
      })
    } else {
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  },
  onPullDownRefresh: function () {
    let that = this
    wx.stopPullDownRefresh()
    that.loadBaby()
  },
  onReachBottom: function () {
    let that = this
    that.loadLog()
  }
})